import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:shop/generated/i18n.dart';
import 'package:shop/http/http_util.dart';
import 'package:shop/http/request_url.dart';
import 'package:shop/model/swiper_bean.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

enum ViewState{
  success
}

//首页
class HomeScreen extends StatefulWidget {
  @override
  HomeScreenState createState() => HomeScreenState();
}

class HomeScreenState extends State<HomeScreen> with AutomaticKeepAliveClientMixin {
  List<String> images = [];
  SwiperController controller = SwiperController();

  @override
  void initState() {
    super.initState();
    debugPrint("执行方法initState()");
    getCarousel();
    controller.startAutoplay();
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("执行方法dispose()");
    controller.stopAutoplay();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('首页'),
        centerTitle: true,
      ),
      body: Container(
        //MediaQuery.of(context).size.width
        width: double.infinity,
        height: 200.0,
        child: Swiper(
          //http://via.placeholder.com/350x150
          itemBuilder: (context, index) {
            return Image.network(images[index], fit: BoxFit.fill);
          },
          itemCount: images.length,
          pagination: new SwiperPagination(
              builder: DotSwiperPaginationBuilder(
            //默认点颜色
            color: Colors.black54,
            //当前点颜色
            activeColor: Colors.grey,
            //默认点大小
            size: 5.0,
            //点与点之间的距离
            space: 1,
            //当前点大小
            activeSize: 6.0,
          )),
          controller: controller,
          scrollDirection: Axis.horizontal,
          loop: false,
          //自动播放
          autoplay: false,
          //自动播放延迟时间
          autoplayDelay: 2000,
          //当用户拖拽时，停止自动播放
          autoplayDisableOnInteraction: true,
          scale: 0.8,
          onTap: (index) => debugPrint('点击了第$index个'),
        ),
      ),
    );
  }

  getCarousel() async {
    var data;
    await HttpUtils().post(RequestUrl().homeCarousel, (result) {
      debugPrint(result);
      final body = json.decode(result);

      final feeds = body['images'];
      List<String> _images = [];
      feeds.forEach((image) {
        _images.add(image['imagePath']);
//        _images.add(new SwiperBean(_image['imageId'], _image['imagePath']));
      });

      setState(() {
        images = _images;
      });
    }, data: data);
  }

  //确保tab切换，不被销毁，必须添加super.build(context)
  @override
  bool get wantKeepAlive => true;
}
